--
-- Author: yawei.zhu
-- Date: 2018-09-11 11:06:56
--
-- DynastyBattleView
--

local TeamMemberInfoVo = require("app.team.models.TeamMemberInfoVo")
local DynastyBattleHeadRender = import(".renders.DynastyBattleHeadRender")
local DynastyBattleMapRender = import(".renders.DynastyBattleMapRender")
local NewguildIconRender = require("app.newGuild.views.renders.NewguildIconRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.DynastyBattleScene
local BATTLE_COUNT = 3
local MEMBER_COUNT = 5

function ClassRef:init()
	self._ui.Button_close:addClickEventListener(function()
		executeFunc(self._onCloseView)
	end)
	self._ui["Panel_r/btn_gp"]:addClickEventListener(function()
		executeFunc(self._onOperate, "enterDynastyBattle")
	end)
	self._ui["Panel_r/btn_guild"]:addClickEventListener(function()
		executeFunc(self._onOperate, "openGuildMember")
	end)

	-- left
	-- self._ui["Panel_money/num"]:setString( UD:getGold() )
	self._ui.Panel_money:setVisible(false)
	self._ui["Panel_r/Panel_top/Panel_data/tlt_3"]:setString(L("dynastybattle_score1"))

	self._txtLeftCount = self._ui["Panel_map/Panel_top/num_1"]
	self._txtLeftName = self._ui["Panel_map/Panel_top/name_1"]

	self._txtRightCount = self._ui["Panel_map/Panel_top/num_2"]
	self._txtRightName = self._ui["Panel_map/Panel_top/name_2"]

	self._txtTips = self._ui["Panel_map/Panel_bom/tips"]
	self._timeClock = self._ui["Panel_map/Panel_bom/icon"]

	self._battleMaps = {}
	for i = 1, BATTLE_COUNT do
		local render = DynastyBattleMapRender.create( self._ui["Panel_map/map_"..i] )
		render:onBtnClick(handler(self, self.onSelectPanel))
		render:setVisible(false)
		self._battleMaps[i] = render
	end
	-- 暂时隐藏第4 第5个节点
	self._ui["Panel_map/map_4"]:setVisible(false)
	self._ui["Panel_map/map_5"]:setVisible(false)

	-- right
	self._battleImage = self._ui["Panel_r/Panel_top/Image"]
	self._battleName = self._ui["Panel_r/Panel_top/name"]
	self._limitNum = self._ui["Panel_r/Panel_top/Panel_data/num_1"]
	self._curLeftNum = self._ui["Panel_r/Panel_top/Panel_data/num_2"]
	self._curRightNum = self._ui["Panel_r/Panel_top/Panel_data/num_3"]
	self._curLeftScore = self._ui["Panel_r/Panel_top/Panel_data/num_4"]
	self._curRightScore = self._ui["Panel_r/Panel_top/Panel_data/num_5"]

	self._teamNodes = {}
	for i = 1, MEMBER_COUNT do
		local render = DynastyBattleHeadRender.create( self._ui["Panel_r/Panel_m/head_"..i] )
		render:onBtnClick(function(data)
			executeFunc(self._onOperate, "openTeamview", data)
		end)
		render:setVisible(false)
		self._teamNodes[i] = render

		self._ui["Panel_r/Panel_m/btn_"..i]:addClickEventListener(function()
			executeFunc(self._onOperate, "openInviteView")
		end)
	end

	-- 进入战场
	self._ui["Panel_r/btn_gp"]:addClickEventListener(function()
		if not self._townInfo then return end
		if not self._townInfo:checkCanEnterByGuildId( UD:getGuildId() ) then
			display.pushToast( L("dynastybattle_score2") )
			return 
		end

		local TeamModel = app:getInst("TeamModel")
		if not TeamModel:hasTeam() then
			executeFunc(self._onOperate, "openTeamview")
			return
		end

		if not TeamModel:isLeader() then
			display.pushToast( L("dynastybattle_score3") )
			return
		end

		executeFunc(self._onOperate, "reqEnterDynastyBattle", {self._townInfo.id, self._curStronghold.id})
	end)
end

-- 移除定时器
function ClassRef:removeScheduler()
	if self._cronsIdx then
		scheduler.cancelCron(self._cronsIdx)
		self._cronsIdx = nil
	end
end

function ClassRef:updateTick()

	local function setBtnEnabled(btn, enabled)
		if btn:isTouchEnabled() == enabled then return end
		display.setBtnTouchEnable(btn, enabled)
	end

	local serverTime = app.session:getServerTime()
	for i = 1, 5 do
		self._teamNodes[i]:updateTick(serverTime)
	end
	-- 是否已结束
	local remainedTime = math.floor(self._townInfo.fightEndTime - serverTime)
	if remainedTime < 0 then remainedTime = 0 end
	if remainedTime <= 0 then -- 已结束
		self._txtTips:setString(L("dynastybattle_score4"))
		display.setNodesMiddle(self._ui["Panel_map/Panel_bom"], nil, self._timeClock, self._txtTips)
		self:removeScheduler()
		setBtnEnabled(self._ui["Panel_r/btn_gp"], false)
		return
	end
	-- 显示时间
	if self._townInfo.fightStartTime > serverTime then
		local str = TimeUtil.secondsToTime( math.floor(self._townInfo.fightStartTime - serverTime) )
		self._txtTips:setString( string.format( L("dynastybattle_score5"), str ) )
		display.setNodesMiddle(self._ui["Panel_map/Panel_bom"], nil, self._timeClock, self._txtTips)
		setBtnEnabled(self._ui["Panel_r/btn_gp"], false)
	else
		local str = TimeUtil.secondsToTime(remainedTime)
		self._txtTips:setString( string.format( L("dynastybattle_score6"), str ) )
		display.setNodesMiddle(self._ui["Panel_map/Panel_bom"], nil, self._timeClock, self._txtTips)
		setBtnEnabled(self._ui["Panel_r/btn_gp"], true)
	end

	-- 拉取该城镇信息
	if not self._tickCount then self._tickCount = 0 end
	self._tickCount = self._tickCount + 1
	if self._tickCount >= 6 then -- 打开战备UI时，每6s拉取一次信息
		executeFunc(self._onOperate, "reqTownInfo", self._townInfo.id)
		self._tickCount = 0
	end
end

-- 打开UI
function ClassRef:updateView(townInfo, strongholdId, teamMembers)
	if not townInfo then return end
	if townInfo.phase ~= "READY" and townInfo.phase ~= "FIGHT" then return end

	local defer = townInfo.defer
	self.guildIconDef = NewguildIconRender.create( self._ui["Panel_map/Panel_top/icon_1"] ) -- 左边公会头像
	self.guildIconDef:setData( {baseIconId = defer.flagBaseIcon, additionIconId = defer.flagAdditionalIcon, baseIconColor = defer.flagBaseIconColor, additionIconColor = defer.flagAdditionalIconColor} ) 

	local atker = townInfo.atker
	self.guildIconAtk = NewguildIconRender.create( self._ui["Panel_map/Panel_top/icon_2"] ) -- 右边公会头像
	self.guildIconAtk:setData( {baseIconId = atker.flagBaseIcon, additionIconId = atker.flagAdditionalIcon, baseIconColor = atker.flagBaseIconColor, additionIconColor = atker.flagAdditionalIconColor} )

	self._curIndex = townInfo:getIndexByStrongholdId(strongholdId)
	self:updateTownInfo(townInfo)
	self:updateTeamMember(teamMembers)

	-- 添加定时器
	self:removeScheduler()
	self._cronsIdx = scheduler.newCron(handler(self, self.updateTick), 1, true)
	self:updateTick() 
end

-- 更新城镇信息
function ClassRef:updateTownInfo(townInfo)
	self._townInfo = townInfo

	-- 默认左边我方,右边是敌方（如果我没有参与战斗，左边为防守方，右边为进攻方）
	self._myIsAtk = false
	local leftInfo = self._townInfo.defer
	local rightInfo = self._townInfo.atker
	local leftScore = self._townInfo.totalScoreDef
	local rightScore = self._townInfo.totalScoreAtk
	-- 如果我是进攻方，则调换
	if UD:getGuildId() == townInfo.atker.guildId then
		self._myIsAtk = true
		leftInfo = self._townInfo.atker
		rightInfo = self._townInfo.defer
		leftScore = self._townInfo.totalScoreAtk
		rightScore = self._townInfo.totalScoreDef
	end

	local defer = self._townInfo.defer
	local atker = self._townInfo.atker

	self._txtLeftName:setString( leftInfo.guildName )
	self._txtLeftCount:setString( leftScore )

	self._txtRightName:setString( rightInfo.guildName )
	self._txtRightCount:setString( rightScore )

	for i = 1, BATTLE_COUNT do
		self._battleMaps[i]:setVisible(true)
		local stronghold = self._townInfo.strongholds[i]
		local color = "bule"
		if self._myIsAtk then
			if stronghold.realSpeedDef > stronghold.realSpeedAtk then
				color = "red"
			end
		else
			if stronghold.realSpeedDef < stronghold.realSpeedAtk then
				color = "red"
			end
		end
		self._battleMaps[i]:setData( {index = i, color = color} )
	end
	self:onSelectPanel(self._curIndex)

end

-- 选择据点
function ClassRef:onSelectPanel(index)
	if not index then index = 1 end
	self._curIndex = index

	for i = 1, BATTLE_COUNT do
		if i == index then
			self._battleMaps[i]:setSelected(true)
		else
			self._battleMaps[i]:setSelected(false)
		end
	end

	self:updateRightInfo()
end

-- 更新据点信息
function ClassRef:updateRightInfo()
	local stronghold = self._townInfo.strongholds[self._curIndex]
	if not stronghold then
		print("Error: stronghold = nil, townId =", self._townInfo.id)
		return
	end
	self._curStronghold = stronghold

	local strongholdConfig = GD:getStrongholdInfoById(stronghold.id)
	self._limitNum:setString( string.format( L("dynastybattle_score7"),  strongholdConfig.memberNum) )
	self._battleName:setString(L(strongholdConfig.name))

	local numL = stronghold.realNumDef
	local numR = stronghold.realNumAtk
	local scoreL = stronghold.realSpeedDef
	local scoreR = stronghold.realSpeedAtk
	if self._myIsAtk then
		numL = stronghold.realNumAtk
		numR = stronghold.realNumDef
		scoreL = stronghold.realSpeedAtk
		scoreR = stronghold.realSpeedDef
	end

	self._curLeftNum:setString(numL)
	self._curRightNum:setString(numR)
	self._curLeftScore:setString(scoreL)
	self._curRightScore:setString(scoreR)
end

-- teamMembers里面的数据是 TeamMemberInfoVo
function ClassRef:updateTeamMember(teamMembers)
	if not self._townInfo then return end

	if not teamMembers or #teamMembers <= 0 then
		local data = {}
		data.userBaseInfo = UD:getAvatarParams()
		data.isLeader = true
		local member = TeamMemberInfoVo.new(data)
		teamMembers = {member}
	end

	local leaderTicket = false
	local leaderGuildId = 0
	for _, member in ipairs(teamMembers) do
		if member:isLeader() then
			leaderGuildId = member:getGuildId()
			leaderTicket = self._townInfo:checkCanEnterByGuildId(leaderGuildId)
			break
		end 
	end

	for i = 1, 5 do
		local btn = self._ui["Panel_r/Panel_m/btn_"..i]
		local head = self._teamNodes[i]

		if teamMembers[i] then
			head:setData(teamMembers[i])
			head:setVisible(true)
			btn:setVisible(false)

			-- 设置门票状态 (当和队长的门票不一致时，设置为false)
			local hasTicket = self._townInfo:checkCanEnterByGuildId(teamMembers[i]:getGuildId())
			if hasTicket and leaderTicket then
				if leaderGuildId ~= teamMembers[i]:getGuildId() then
					hasTicket = false
				end
			end

			head:showTicket(hasTicket)
		else
			self._teamNodes[i]:setVisible(false)
			btn:setVisible(true)
		end
	end

	-- 队伍总战力
	local totalPower = 0
	for i, member in ipairs(teamMembers) do
		totalPower = totalPower + member.userBaseInfo.combatPower
	end
	self._ui["Panel_r/Panel_m/tips"]:setString( string.format( L("dynastybattle_score8"), totalPower) )

	self:updateTick()
end

-- 关掉界面时，移除定时器
function ClassRef:onExit()
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end

    self.super.onExit(self)
end

return ClassRef
